package com.lujieni.springbootwebsocket.controller;

import com.lujieni.springbootwebsocket.dto.WebsiteMsgDTO;
import com.lujieni.springbootwebsocket.server.WebSocketServer;
import com.lujieni.springbootwebsocket.service.WebsiteMsgSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.client.WebSocketClient;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/4/27 15:47
 * @Description:
 */
@RestController
public class MessageController {

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private WebsiteMsgSender websiteMsgSender;

    @GetMapping(value = "/broadcast")
    public void sendMessge(String message){
        webSocketServer.broadcast(message);
    }

    /**
     * 单体架构可行
     * @param message
     * @param userCode
     * @return
     */
    @GetMapping(value = "/sendMessageToSpecificClient")
    public String sendMessageToSpecificClient(String message, String userCode){
        try {
            Session session = webSocketServer.checkIsOnline(userCode);
            if(session != null){
                webSocketServer.sendMessageToSpecificClient(message, session);
                return "发送成功";
            }else{
                return "用户不在线,无法发送";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping(value = "/sendMessageToSpecificClientByMq")
    public String sendMessageToSpecificClientByMq(String message, String userCode) {
        websiteMsgSender.sendMsg(new WebsiteMsgDTO(userCode, message));
        return "发送成功";
    }

}
